package com.retail.system.service.impl;

import cn.binarywang.wx.miniapp.api.WxMaService;
import cn.hutool.core.bean.BeanUtil;
import cn.hutool.core.date.DateUtil;
import cn.hutool.core.io.FileUtil;
import cn.hutool.core.util.ObjectUtil;
import cn.hutool.core.util.StrUtil;
import com.retail.core.cache.CacheService;
import com.retail.core.entity.CommonEntity;
import com.retail.core.entity.ParamReq;
import com.retail.core.entity.enums.DelFlagEnum;
import com.retail.core.entity.enums.StatusFlagEnum;
import com.retail.core.entity.result.Result;
import com.retail.core.exception.custom.SaveException;
import com.retail.core.util.CommonConstants;
import com.retail.proxy.entity.request.AdminProxyUpgradeDetailRequest;
import com.retail.proxy.entity.request.SysAdminProxyUpgradeRequest;
import com.retail.proxy.entity.vo.ProxyMechanismCategoryVo;
import com.retail.proxy.entity.vo.ProxyUpgradeConfigVo;
import com.retail.proxy.mapper.AdminProxyUpgradeDetailMapper;
import com.retail.proxy.mapper.ProxyMechanismCategoryMapper;
import com.retail.proxy.mapper.ProxyUpgradeConfigMapper;
import com.retail.proxy.mapper.SysAdminProxyUpgradeMapper;
import com.retail.proxy.util.ShareCodeUtils;
import com.retail.shop.entity.request.RetailAdminShopRequest;
import com.retail.shop.entity.request.RetailShopRequest;
import com.retail.shop.entity.vo.RetailAdminShopVo;
import com.retail.shop.entity.vo.RetailShopVo;
import com.retail.shop.enums.ExamineVerifyEnums;
import com.retail.shop.enums.ShopSourceEnums;
import com.retail.shop.mapper.RetailAdminShopMapper;
import com.retail.shop.mapper.RetailShopMapper;
import com.retail.system.entity.po.AdminPo;
import com.retail.system.entity.po.AdminRolePo;
import com.retail.system.entity.po.RolePo;
import com.retail.system.entity.request.AdminRequest;
import com.retail.system.entity.request.AdminUpdatePassRequest;
import com.retail.system.entity.vo.AdminStatisticsPersonVo;
import com.retail.system.entity.vo.AdminVo;
import com.retail.system.entity.vo.DeptVo;
import com.retail.system.entity.vo.FileVo;
import com.retail.system.enums.AuditStatusEnums;
import com.retail.system.enums.UserTypeEnums;
import com.retail.system.mapper.AdminMapper;
import com.retail.system.mapper.AdminPermitMapper;
import com.retail.system.mapper.AdminRoleMapper;
import com.retail.system.mapper.DeptMapper;
import com.retail.system.service.AdminService;
import com.retail.system.service.FileService;
import com.retail.team.entity.vo.RetailTeamAddSpVo;
import com.retail.team.enums.VerifyFlagEnums;
import me.chanjar.weixin.common.error.WxErrorException;
import org.springframework.mock.web.MockMultipartFile;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.util.DigestUtils;
import org.springframework.web.multipart.MultipartFile;

import javax.annotation.Resource;
import java.io.File;
import java.io.IOException;
import java.util.Date;
import java.util.HashSet;
import java.util.List;
import java.util.Set;
import java.util.stream.Collectors;

/**
 * @author Administrator
 * @since 2019-05-25
 */
@Service("adminService")
public class AdminServiceImpl implements AdminService {

    @Resource
    private AdminMapper adminMapper;

    @Resource
    private AdminRoleMapper adminRoleMapper;

    @Resource
    private AdminPermitMapper adminPermitMapper;

    @Resource
    private DeptMapper deptMapper;

    @Resource
    private RetailAdminShopMapper retailAdminShopMapper;

    @Resource
    private ProxyMechanismCategoryMapper proxyMechanismCategoryMapper;

    @Resource
    private FileService fileService;

    /**
     * 默认密码
     */
    public final static String DEFAULT_PASSWORD = "123456";

    @Resource
    private WxMaService wxMaService;

    @Resource
    private RetailShopMapper retailShopMapper;

    @Resource
    private CacheService cacheService;


    @Override
    public Integer updateDelFlagById(Long id, Integer delFlag) {
        return adminMapper.updateDelFlagById(id, delFlag);
    }

    @Override
    public List<AdminVo> listPage(ParamReq<AdminRequest> params) {
        List<AdminVo> adminVos = adminMapper.listPage(params);
        adminVos.forEach(admin -> {
            adminRoles(admin);
            // 设置单位信息
            admin.setDeptName(getDeptName(admin.getDeptId()));
            admin.setStatusName(StatusFlagEnum.getStatusValues(admin.getStatusFlag()));
            if (ObjectUtil.isNotEmpty(admin.getAdminLevel())) {
                ProxyMechanismCategoryVo proxyCategory = proxyMechanismCategoryMapper.getModel(admin.getAdminLevel());
                if (ObjectUtil.isNotEmpty(proxyCategory)) {
                    admin.setAdminLevelName(proxyCategory.getCategoryName());
                }
            }

            setParentAdmin(admin);
//            adminVo.setPass(StrUtil.EMPTY);
        });

        return adminVos;
    }


    @Override
    public Integer countPage(ParamReq<AdminRequest> map) {
        return adminMapper.countPage(map);
    }

    @Override
    public AdminPo getModelByUserName(String usename) {
        if (StrUtil.isEmpty(usename)) {
            return null;
        }
        return adminMapper.getModelByUserName(usename);
    }

    @Override
    public AdminVo getUseByOpenId(String openId) {
        AdminVo adminVo = adminMapper.getUserByOpenId(openId);
//        if(ObjectUtil.isNotEmpty(adminVo)) {
//            if (!cacheService.hasKey(adminVo.getPromoCode())) {
//                String promoCodeUrl = createPromoCodeUrl(adminVo.getPromoCode());
//                cacheService.add(adminVo.getPromoCode(), promoCodeUrl, 6, TimeUnit.DAYS);
//                adminMapper.updatePromoCodeUrlById(adminVo.getId(), promoCodeUrl);
//            }
//        }
        return adminVo;
    }

    @Override
    public AdminVo getModel(Long id) {
        AdminVo adminVo = adminMapper.getModel(id);
        adminRoles(adminVo);
        // 设置单位信息
        adminVo.setDeptName(getDeptName(adminVo.getDeptId()));
        adminVo.setStatusName(StatusFlagEnum.getStatusValues(adminVo.getStatusFlag()));
        adminVo.setPass(StrUtil.EMPTY);

        setParentAdmin(adminVo);

        if (ObjectUtil.isNotEmpty(adminVo.getAdminLevel())) {
            ProxyMechanismCategoryVo proxyCategory = proxyMechanismCategoryMapper.getModel(adminVo.getAdminLevel());
            if (ObjectUtil.isNotEmpty(proxyCategory)) {
                adminVo.setAdminLevelName(proxyCategory.getCategoryName());
            }
        }

        return adminVo;
    }

    /**
     * 设置上级用户
     *
     * @param adminVo
     */
    private void setParentAdmin(AdminVo adminVo) {
        if (ObjectUtil.isNotEmpty(adminVo.getParentId())) {
            AdminVo pAdminvo = adminMapper.getModel(adminVo.getParentId());
            if (ObjectUtil.isNotEmpty(pAdminvo)) {
                adminVo.setParentName(pAdminvo.getName());
            }
        }
    }

    private void adminRoles(AdminVo adminVo) {
        List<RolePo> roles = adminRoleMapper.getRoleByAdminId(adminVo.getId());
        Set<Long> roleIds = roles.stream().filter(ObjectUtil::isNotEmpty).map(CommonEntity::getId).collect(Collectors.toSet());
        adminVo.setRoleIds(roleIds);

        String roleNames = roles.stream().map(RolePo::getRoleName).collect(Collectors.joining(","));
        adminVo.setRoleNames(roleNames);
    }

    /**
     * 设置单位名称
     *
     * @param userId 用户编号
     * @return 机构编号
     */
    private String getDeptName(Long userId) {
        DeptVo deptvo = deptMapper.getModel(userId);
        return ObjectUtil.isNotEmpty(deptvo) ? deptvo.getDeptName() : null;
    }

    @Transactional(rollbackFor = SaveException.class)
    @Override
    public Long save(AdminRequest request) {
        request.setPass(DigestUtils.md5DigestAsHex(DEFAULT_PASSWORD.getBytes()));
        request.setPromoCode(ShareCodeUtils.idToCode(1L));
        createPromoCode(request);

        String promoCodeUrl = createPromoCodeUrl(request.getPromoCode());
//        cacheService.add(request.getPromoCode(), promoCodeUrl, 6, TimeUnit.DAYS);
        adminMapper.save(request);
        updateRoles(request.getId(), request.getCreateUser(), request.getRoleIds());
        updatePermits(request.getId(), request.getCreateUser(), request.getRoleIds());
        return request.getId();
    }

    private void createPromoCode(AdminRequest request) {
        request.setPromoCodeUrl(createPromoCodeUrl(request.getPromoCode()));
    }



    private String createPromoCodeUrl(String promoCode) {
        File qrcode = null;
        try {
            qrcode = wxMaService.getQrcodeService()
                    .createWxaCodeUnlimit(promoCode,
                            "pages/user/index",
                            ".",
                            false,
                            "release",
//                            "trial",    // developer trial  formal
                            430, true, null, false);
            try {
                MultipartFile multipartFile = new MockMultipartFile(promoCode + ".jpg", promoCode + ".jpg", "image/jpeg", FileUtil.getInputStream(qrcode));
                Result res = fileService.uploadFile(new MultipartFile[]{multipartFile});
                if (ObjectUtil.equal(res.getCode(), 200)) {
                    FileVo fileVo = (FileVo) res.getData();
                    String local = fileVo.getLocation();
                    return local;
                }
            } catch (IOException e) {
                e.printStackTrace();
            }
        } catch (WxErrorException e) {
            e.printStackTrace();
        }
        return "";
    }

    @Transactional(rollbackFor = Exception.class)
    @Override
    public Long update(AdminRequest request) {
        updateRoles(request.getId(), request.getCreateUser(), request.getRoleIds());
        updatePermits(request.getId(), request.getCreateUser(), request.getRoleIds());
        adminMapper.updateById(request);
        return request.getId();
    }

    @Transactional(rollbackFor = Exception.class)
    @Override
    public Integer updatePassword(AdminUpdatePassRequest adminUpdatePassRequest) {
        try {
            String oldPass = DigestUtils.md5DigestAsHex(adminUpdatePassRequest.getOldPassword().getBytes());
            AdminPo adminPo = adminMapper.getModel(adminUpdatePassRequest.getId());
            if (ObjectUtil.equal(adminPo.getPass(), oldPass)) {
                String newPass = DigestUtils.md5DigestAsHex(adminUpdatePassRequest.getOldPassword().getBytes());
                return adminMapper.updatePassById(adminPo.getId(), newPass);
            } else {
                return 2;
            }
        } catch (Exception e) {
            return 0;
        }
    }

    /**
     * 修改角色信息
     *
     * @param userId     用户编号
     * @param createUser 创建用户
     * @param roles      角色集合
     */
    private void updateRoles(Long userId, Long createUser, Set<Long> roles) {
        // 更新用户角色表和权限表
        adminRoleMapper.updateRoleByAdminId(userId);
        AdminRolePo adminRolePo = new AdminRolePo();
        adminRolePo.setAdminId(userId);
        adminRolePo.setRoleIds(roles);
        adminRolePo.setCreateUser(createUser);
        adminRolePo.setDelFlag(DelFlagEnum.NO.getValue());
        adminRoleMapper.batchSave(adminRolePo);
    }

    /**
     * 更新权限信息
     *
     * @param userId     用户编号
     * @param createUser 创建人
     * @param roles      角色编号
     */
    private void updatePermits(Long userId, Long createUser, Set<Long> roles) {
        adminPermitMapper.updatePermitByAdminId(userId);
        adminPermitMapper.insertAdminPermits(userId, roles, createUser);
    }

    /**
     * 验证手机号码和openid是否已被注册
     *
     * @param adminRequest
     * @return
     */
    @Override
    @Transactional
    public Result registerUser(AdminRequest adminRequest) {
        // 判断用户 openid和手机号码是否已经存在 同时存在，并且审核已经通过，状态有效 未删除，如果存在直接返回，提示用户登录
        Integer cnt = adminMapper.checkMobileAndOpenIdIsRegister(adminRequest.getPhone(), adminRequest.getOpenId());
        if (cnt > 0) {
            return Result.fail("请不要重复注册哦，您可以直接登录系统！");
        }
        // 验证手机号码是否已经注册并且状态有效，如果有效提示用户，手机号码已经被注册，找管理员解绑
        cnt = adminMapper.checkMobileIsRegister(adminRequest.getPhone());
        if (cnt > 0) {
            return Result.fail("手机号码已被注册，请联系管理管理处理！");
        }
        // 验证openid是否已经注册并且状态有效，如果有效提示用户，微信已经被注册，找管理员解绑
        cnt = adminMapper.checkOpenIdIsRegister(adminRequest.getOpenId());
        if (cnt > 0) {
            return Result.fail("微信已经被其他手机号码注册，请联系管理管理处理");
        }
        // 验证用户名是否被使用
        cnt = adminMapper.checkUsernameIsUse(adminRequest.getUsername());
        if (cnt > 0) {
            return Result.fail("手机号码已经被使用，换一个试试！");
        }

        // 注册，并添加权限
        // 设置角色 和 部门
        Set<Long> role = new HashSet<>();
        if (ObjectUtil.equal(adminRequest.getUserType(), 1)) {
            role.add(CommonConstants.BUSSINESS_ROLE);
        } else if (ObjectUtil.equal(adminRequest.getUserType(), 2)) {
            adminRequest.setAuditStatus(AuditStatusEnums.VERIFY_SUCCESS.getValue());
            role.add(CommonConstants.SHOP_ROLE);
        }
        adminRequest.setRoleIds(role);
        Set<Long> deptId = new HashSet<>();
        deptId.add(CommonConstants.DEPT_ID);
        adminRequest.setDeptIds(deptId);
        adminRequest.setStatusFlag(1);
        adminRequest.setAuditStatus(0);
        adminRequest.setDelFlag(0);
        adminRequest.setCreateUser(0L);
        adminRequest.setUpgradeLevel(0L);
        adminRequest.setUpgradePreLevel(0L);
        adminRequest.setUpgradeTime(DateUtil.format(new Date(), "yyyy-MM-dd"));

        // 根据otPromoCode 转换ID
        if (ObjectUtil.isNotEmpty(adminRequest.getOtPromoCode())) {
            AdminVo parentAdminVo = adminMapper.getUserByPromoCode(adminRequest.getOtPromoCode());
            if (ObjectUtil.isNotEmpty(parentAdminVo)) {
                adminRequest.setParentId(parentAdminVo.getId());
            }
        }
        Long ownerId = this.save(adminRequest);
        return Result.success("注册成功，请等待管理员的审核");
    }

    /**
     * 更新用户信息
     *
     * @param adminRequest
     * @return
     */
    @Override
    public Result updateUserInfo(AdminRequest adminRequest) {
        adminMapper.updateById(adminRequest);

        RetailShopVo oldShopVo = retailShopMapper.getAllStatusOwnerModelByPoiId(adminRequest.getPoiId());
        if (ObjectUtil.isNotEmpty(oldShopVo) && ObjectUtil.notEqual(oldShopVo.getOwnerId(), adminRequest.getId())) {
            return Result.fail("该商户已经注册了，请核实信息！");
        }

        AdminVo adminVo = adminMapper.getModel(adminRequest.getId());
        if (ObjectUtil.equal(adminVo.getUserType(), UserTypeEnums.SHOP_TYPE.getValue())) {
            RetailShopVo shopVo = retailShopMapper.getOwnerShopByOwnerId(adminVo.getId());
            Long shopId = null;
            if (ObjectUtil.isEmpty(shopVo)) {
                RetailShopRequest shopRequest = new RetailShopRequest();
                shopRequest.setOwnerId(adminVo.getId());
                shopRequest.setShopSource(ShopSourceEnums.OWNER_TYPE.getValue());
                shopRequest.setPoiId(adminRequest.getPoiId());
                shopRequest.setPoiName(adminRequest.getPoiName());
                shopRequest.setAddress(adminRequest.getAddress());

                shopRequest.setCorporation(adminRequest.getCorporation());
                shopRequest.setCorporationPhone(adminRequest.getCorporationPhone());
                shopRequest.setStorePhone(adminRequest.getStorePhone());
                shopRequest.setBusinessLicense(adminRequest.getBusinessLicense());
                if (ObjectUtil.isNotEmpty(adminRequest.getSanitaryLicensePhotos()) && adminRequest.getSanitaryLicensePhotos().size() >0) {
                    shopRequest.setSanitaryLicensePhoto(adminRequest.getSanitaryLicensePhotos().stream().collect(Collectors.joining(",")));
                }

                shopRequest.setDredgeDouyin(adminRequest.getDredgeDouyin());
                shopRequest.setDredgeBuy(adminRequest.getDredgeBuy());
                if (ObjectUtil.isNotEmpty(adminRequest.getBusinessLicensePhotos()) && adminRequest.getBusinessLicensePhotos().size() >0 ) {
                    shopRequest.setBusinessLicensePhoto(adminRequest.getBusinessLicensePhotos().stream().collect(Collectors.joining(",")));
                }

                if (ObjectUtil.isNotEmpty(adminRequest.getCorporationPhotos()) && adminRequest.getCorporationPhotos().size()>0) {
                    shopRequest.setCorporationPhoto(adminRequest.getCorporationPhotos().stream().collect(Collectors.joining(",")));
                }

                shopRequest.setCorporationCard(adminRequest.getCorporationCard());
                shopRequest.setCorporationCardBank(adminRequest.getCorporationCardBank());

                if (ObjectUtil.isNotEmpty(adminRequest.getDoorPhotos()) && adminRequest.getDoorPhotos().size() >0) {
                    shopRequest.setDoorPhoto(adminRequest.getDoorPhotos().stream().collect(Collectors.joining(",")));
                }

                if (ObjectUtil.isNotEmpty(adminRequest.getEvnPhotos()) && adminRequest.getEvnPhotos().size() >0) {
                    shopRequest.setEvnPhoto(adminRequest.getEvnPhotos().stream().collect(Collectors.joining(",")));
                }

                if (ObjectUtil.isNotEmpty(adminRequest.getDouyinPhotos()) && adminRequest.getDouyinPhotos().size() >0) {
                    shopRequest.setDouyinPhoto(adminRequest.getDouyinPhotos().stream().collect(Collectors.joining(",")));
                }

                shopRequest.setDeliveryAddress(adminRequest.getDeliveryAddress());

                shopRequest.setBusinessHour(adminRequest.getBusinessHour());


                // TODO: 2024/7/28 先默认通过，不需要审核
                shopRequest.setStatusFlag(StatusFlagEnum.USE.getValue());
                shopRequest.setDelFlag(DelFlagEnum.NO.getValue());
                retailShopMapper.save(shopRequest);
                shopId = shopRequest.getId();
            } else {
                shopVo.setPoiId(adminRequest.getPoiId());
                shopVo.setPoiName(adminRequest.getPoiName());
                shopVo.setAddress(adminRequest.getAddress());
                RetailShopRequest shopRequest = new RetailShopRequest();
                BeanUtil.copyProperties(shopVo, shopRequest);
                shopRequest.setCorporation(adminRequest.getCorporation());
                shopRequest.setCorporationPhone(adminRequest.getCorporationPhone());
                shopRequest.setStorePhone(adminRequest.getStorePhone());
                shopRequest.setBusinessLicense(adminRequest.getBusinessLicense());
                if (ObjectUtil.isNotEmpty(adminRequest.getSanitaryLicensePhotos()) && adminRequest.getSanitaryLicensePhotos().size() >0) {
                    shopRequest.setSanitaryLicensePhoto(adminRequest.getSanitaryLicensePhotos().stream().collect(Collectors.joining(",")));
                }

                shopRequest.setDredgeDouyin(adminRequest.getDredgeDouyin());
                shopRequest.setDredgeBuy(adminRequest.getDredgeBuy());
                if (ObjectUtil.isNotEmpty(adminRequest.getBusinessLicensePhotos()) && adminRequest.getBusinessLicensePhotos().size() >0 ) {
                    shopRequest.setBusinessLicensePhoto(adminRequest.getBusinessLicensePhotos().stream().collect(Collectors.joining(",")));
                }

                if (ObjectUtil.isNotEmpty(adminRequest.getCorporationPhotos()) && adminRequest.getCorporationPhotos().size()>0) {
                    shopRequest.setCorporationPhoto(adminRequest.getCorporationPhotos().stream().collect(Collectors.joining(",")));
                }

                shopRequest.setCorporationCard(adminRequest.getCorporationCard());
                shopRequest.setCorporationCardBank(adminRequest.getCorporationCardBank());

                if (ObjectUtil.isNotEmpty(adminRequest.getDoorPhotos()) && adminRequest.getDoorPhotos().size() >0) {
                    shopRequest.setDoorPhoto(adminRequest.getDoorPhotos().stream().collect(Collectors.joining(",")));
                }

                if (ObjectUtil.isNotEmpty(adminRequest.getEvnPhotos()) && adminRequest.getEvnPhotos().size() >0) {
                    shopRequest.setEvnPhoto(adminRequest.getEvnPhotos().stream().collect(Collectors.joining(",")));
                }

                if (ObjectUtil.isNotEmpty(adminRequest.getDouyinPhotos()) && adminRequest.getDouyinPhotos().size() >0) {
                    shopRequest.setDouyinPhoto(adminRequest.getDouyinPhotos().stream().collect(Collectors.joining(",")));
                }

                shopRequest.setDeliveryAddress(adminRequest.getDeliveryAddress());

                shopRequest.setBusinessHour(adminRequest.getBusinessHour());


                retailShopMapper.update(shopRequest);
                shopId = shopRequest.getId();
            }

            Long parentId = adminVo.getParentId();
            RetailAdminShopVo adminShop = retailAdminShopMapper.getModelByAdminIdAndShopId(parentId, shopId);
            if (ObjectUtil.isEmpty(adminShop)) {
                RetailAdminShopRequest ras = new RetailAdminShopRequest();
                ras.setAdminId(parentId);
                ras.setShopId(shopId);
                ras.setExamineVerify(ExamineVerifyEnums.EXAMINE_VERIFIED.getValue());
                ras.setStatusFlag(StatusFlagEnum.USE.getValue());
                ras.setDelFlag(DelFlagEnum.NO.getValue());
                retailAdminShopMapper.save(ras);
            }

            return Result.success("更新商户信息成功!");
        }
        return Result.success("更新用户信息成功!");
    }

    @Resource
    private ProxyUpgradeConfigMapper proxyUpgradeConfigMapper;

    @Resource
    private SysAdminProxyUpgradeMapper sysAdminProxyUpgradeMapper;

    @Resource
    private AdminProxyUpgradeDetailMapper adminProxyUpgradeDetailMapper;

    @Override
    public Result<Integer> examineVerify(AdminRequest request) {
        Integer count = adminMapper.examineVerify(request);
        if (ObjectUtil.equal(request.getAuditStatus(), AuditStatusEnums.VERIFY_SUCCESS.getValue())) {
            saveUpgradeLog(request.getId());
        }


        return Result.success(count);
    }

    /**
     * 晋升等级
     *
     * @param adminId
     */
    private void saveUpgradeLog(Long adminId) {
        AdminVo currentUser = adminMapper.getModel(adminId);
        AdminVo parentUser = null;
        if (ObjectUtil.isNotEmpty(currentUser.getParentId())) {
            parentUser = adminMapper.getModel(currentUser.getParentId());
            List<AdminVo> childAdmins = adminMapper.getModelByParentAndAdminLevel(currentUser.getParentId(), currentUser.getAdminLevel());

            ProxyUpgradeConfigVo upgradeConfigVo = proxyUpgradeConfigMapper.getModelByOraCategoryId(currentUser.getAdminLevel());
            if (ObjectUtil.isNotEmpty(childAdmins) && ObjectUtil.isNotEmpty(upgradeConfigVo)) {
                if (childAdmins.size() >= upgradeConfigVo.getUpgradeCount() && parentUser.getAdminLevel() < upgradeConfigVo.getCategoryId()) {
                    SysAdminProxyUpgradeRequest sysAdminProxyUpgradeRequest = new SysAdminProxyUpgradeRequest();
                    sysAdminProxyUpgradeRequest.setAdminId(parentUser.getId());
                    sysAdminProxyUpgradeRequest.setOraCategoryId(parentUser.getAdminLevel());
                    sysAdminProxyUpgradeRequest.setCategoryId(upgradeConfigVo.getCategoryId());
                    sysAdminProxyUpgradeRequest.setVerifyFlag(VerifyFlagEnums.DAI_SHEN_HE.getValue());
                    sysAdminProxyUpgradeRequest.setStatusFlag(StatusFlagEnum.USE.getValue());
                    sysAdminProxyUpgradeRequest.setDelFlag(DelFlagEnum.NO.getValue());

                    sysAdminProxyUpgradeMapper.save(sysAdminProxyUpgradeRequest);

                    Long upgradeId = sysAdminProxyUpgradeRequest.getId();
                    childAdmins.forEach(cadmin -> {
                        AdminProxyUpgradeDetailRequest adminProxyUpgradeDetailRequest = new AdminProxyUpgradeDetailRequest();
                        adminProxyUpgradeDetailRequest.setAdminId(cadmin.getId());
                        adminProxyUpgradeDetailRequest.setUpgradeId(upgradeId);
                        adminProxyUpgradeDetailRequest.setCategoryId(cadmin.getAdminLevel());
                        adminProxyUpgradeDetailRequest.setStatusFlag(StatusFlagEnum.USE.getValue());
                        adminProxyUpgradeDetailRequest.setDelFlag(DelFlagEnum.NO.getValue());
                        adminProxyUpgradeDetailMapper.save(adminProxyUpgradeDetailRequest);
                    });
                }
            }
        }
    }

    @Override
    public List<AdminVo> childAdminByParentId(Long adminId) {
        return adminMapper.getChildByParentId(adminId);
    }

    @Override
    public List<AdminVo> childAdminByParentIdAndId(Long adminId) {
        return adminMapper.childAdminByParentIdAndId(adminId);
    }

    @Override
    public AdminVo getModelByPoiId(String poiId) {
        return adminMapper.getModelByPoiId(poiId);
    }

    @Override
    public Integer authInfo(String urlZm, String urlFm, Long id) {
        return adminMapper.authInfo(urlZm, urlFm, id);
    }

    @Override
    public List<AdminVo> noParentIdAdmin() {
        return adminMapper.noParentIdAdmin();
    }

    @Override
    public RetailTeamAddSpVo findTeamSpLimit1(Long adminId) {
        return adminMapper.findTeamSpLimit1(adminId);
    }

    @Override
    public List<AdminVo> myteams(Long adminId) {
        List<AdminVo> teams = adminMapper.myteams(adminId);
        teams.forEach(team -> {
            setParentAdmin(team);
        });

        return teams;
    }

    @Override
    public List<AdminVo> findAdminsByUserTypeAndAdminLevel(Integer userType, int adminLevel) {
        return adminMapper.findAdminsByUserTypeAndAdminLevel(userType, adminLevel);
    }

    @Override
    public Integer updateUpgradeLevel(AdminVo admin) {
        return adminMapper.updateUpgradeLevel(admin);
    }

    @Override
    public AdminStatisticsPersonVo statisticsPerson(Long id) {
        return adminMapper.statisticsPerson(id);
    }

    @Override
    public Integer updateCity(Long id, String city) {
        return adminMapper.updateCity(id, city);
    }

    @Override
    public Integer allYwy() {
        return adminMapper.allYwy();
    }
}
